var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}

let operationList=[];
let deptOperationList=[];

(function () {
    let treeList = getCurrentDepartmentUser();
    if(treeList && treeList.list){
        let operationTree = getAllJson(treeList.list);
        operationList=getxmselect("#operationCode","operationCode", operationTree)
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}])
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
    }

})()


layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("BillingStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/Money/tpl/billingStatistics1.jsp","供应商开票统计");
                break
            case "s2":
                parent.intab("views/jsp/Money/tpl/billingStatistics2.jsp","客户开票统计");
                break
            case "s3":
                parent.intab("views/jsp/Money/tpl/billingPurchaseStatistics.jsp","采购开票统计");
                break
        }
    });
})

form.render();//表单刷新
layer.ready(function () {

    //获取所有公司信息名称
    $.ajax({
        url:'billing/findAllCompany',
        success:function(data){
            if(data.status==200){
                for (let i in data.data){
                    $('#billingTowerHeadCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

});
let tempStartCreateDate=$("#startCreateDate").attr("value");
let tempEndCreateDate=$("#endCreateDate").attr("value");
table.render({
    elem: '#makeoutaninvoiceselect'
    ,url:'billing/findBillingListByPage'
    ,toolbar: '#makeoutaninvoicetoolbar'
    , where: {
        operationCode : user.code,
        startCreateDate:tempStartCreateDate ,
        endCreateDate:tempEndCreateDate

    }
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true, totalRowText: '合计'}
        ,{field:'code', title:'开票编号',sort:true,width: 200,event: "moaiserialnumber"}
        ,{field:'contactName', title:'联系人',sort:true,width: 120}
        ,{field:'manufacturerName', title:'名称',sort:true,width: 120}
        ,{field:'billingDateStr', title:'发票收到/开票日期',sort:true,width: 170}
        ,{field:'createDateStr', title:'创建日期',sort:true,width: 120}
        ,{field:'declarationInvoiceCode', title:'单号',sort:true,width: 120}
        ,{field:'currencyName', title:'币种',sort:true,width: 120}
        ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
        ,{field:'totalInvoicedAmount', title:'开票总额',sort:true,width: 120, totalRow: true}
        ,{field:'notificationAmount', title:'通知金额',sort:true,width: 120, totalRow: true}
        ,{field:'openedAmount', title:'已开金额',sort:true,width: 120, totalRow: true}
        ,{field:'uncommittedAmount', title:'未开金额',sort:true,width: 120, totalRow: true}
        ,{field:'increaseCode', title:'增票号',sort:true,width: 120}
        ,{field:'contractCode', title:'销售合同号',sort:true,width: 120}
        ,{field:'purchaseOrderCode', title:'采购合同号',sort:true,width: 120}
        ,{field:'customerArticleCode', title:'客户合同号',sort:true,width: 120}
        ,{field:'customerContractCode', title:'客户货号',sort:true,width: 120}
        ,{field:'billingTowerHeadName', title:'开票抬头',sort:true,width: 120}
        ,{field:'bankName', title:'开票银行',sort:true,width: 120}
        ,{field:'operatorName', title:'操作员',sort:true,width: 120}
        ,{field:'status', title:'单据类型',sort:true,width: 120,templet: function (d) {
                if (d.status==1){
                    return '登记箱';
                }else if (d.status==2){
                    return "完成箱";
                }
            }}
        ,{field:'sourceType', title:'开票类型',width: 120, templet: function (d) {
                if (d.sourceType==1){
                    return '供应商票';
                }else if (d.sourceType==2){
                    return "客户票";
                }
            }}
        ,{fixed: 'right', width:240, toolbar: '#makeoutaninvoiceeditor', title:'操作'}
    ]]
    ,id: 'makeoutaninvoicetableid'
    ,height: $(document).height() - $('#makeoutaninvoiceselect').offset().top - 50
    ,page: true
});


table.on('tool(makeoutaninvoicetable)', function(obj){
    var data = obj.data;
    var id=data.id;
    let sourceType=data.sourceType;
    if(obj.event === 'update') {
        parent.intab("views/jsp/Money/tpl/newupmakeUpdate.jsp?id="+obj.data.id+"&sourceType="+sourceType,"修改开票")
    }else if(obj.event === 'delete'){
        let ids=[];
        ids.push(id);
        layer.confirm('确定的删除么', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(ids),
                async:false,
                url:"billing/updateBillingValidById",
                success:function(res) {
                    if (res.status == 200) {
                        obj.del();
                        layer.close(index);
                        layer.msg('删除成功');
                    }else {
                        layer.msg('删除失败');
                    }
                }
            });


        });

    }else if(obj.event === 'back'){
        layer.confirm('确定退回吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                // contentType: 'application/json',
                data: {id:id,status:1},
                async:false,
                url:"billing/updateBillingStatusById",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("makeoutaninvoicetableid");
                        layer.msg('退回');
                    }else {
                        layer.msg('退回失败');
                    }
                }
            });

        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                // contentType: 'application/json',
                data: {id:id,status:2},
                async:false,
                url:"billing/updateBillingStatusById",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("makeoutaninvoicetableid");
                        layer.msg('完成');
                    }else {
                        layer.msg('完成失败');
                    }
                }
            });

        });
    }else if (obj.event === "moaiserialnumber"){
        let titleSer="";
        if (sourceType==1){
            titleSer="供应商开票明细";
        }else if (sourceType==2){
            titleSer="客户开票明细";
        }
        parent.intab("views/jsp/Money/tpl/viewmakeoutaninvoice.jsp?id="+id+"&sourceType="+sourceType,titleSer);
    }
});

form.on('submit(submitform)', function(data){
    table.reload('makeoutaninvoicetableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

table.on('toolbar(makeoutaninvoicetable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/Money/tpl/newupmakeoutaninvoice.jsp?sourceType=1","新增供应商票");
            break;
        case 'newsCustomer':
            parent.intab("views/jsp/Money/tpl/newupmakeoutaninvoice.jsp?sourceType=2","新增客户票");
            break;
        case 'dels':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList!=''){
                let ids=[];
                layer.confirm('确定删除所选项吗？',function (index) {
                    var cbList = table.cache["makeoutaninvoicetableid"];
                    for(var i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                ids.push(cbList[i].id);
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    $.ajax({
                        type:"POST",
                        dataType:"json",
                        contentType: 'application/json',
                        data:JSON.stringify(ids),
                        async:false,
                        url:"billing/updateBillingValidById",
                        success:function(res) {
                            if (res.status == 200) {
                                table.reload("makeoutaninvoicetableid");
                                layer.msg('删除成功');
                            }
                        }
                    });
                })


            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
        case 'dayin':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个开票单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的开票单据! ");
                break;
            }
            window.open("views/jsp/report.jsp?ym=billingReport&code=code:"+checkStatus.data[0].code)
            break;
    };
});
document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    deptOperationList.setValue([ ]);
};
$("#statistical").on("click",function () {
    parent.intab("views/jsp/Money/tpl/statistics.jsp","厂商开票统计")
});